package controllers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import models.Message;
import models.News;
import models.Product;
import models.ProductType;
import play.Logger;
import play.data.validation.Valid;
import play.data.validation.Validation;
import play.db.jpa.JPABase;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.Router;

/**
 * 
 * 前端界面
 * 
 * @author popoer
 * 
 */
public class Front extends Controller {
	
	private static Whitelist whitelist;
	
	static{
		whitelist = Whitelist.relaxed();
    	whitelist.addTags("iframe","embed");
    	whitelist.addAttributes("iframe", "src","width","height","frameborder");
    	whitelist.addAttributes("embed", "src","width","height","allowscriptaccess","allowfullscreen");
	}

	@Before
	public static void setProductTypes() {
		ProductType rootProductType = ProductType.findById(ProductType
				.getRootId());
		StringBuffer productTree = new StringBuffer();
		buildProductTree(productTree, rootProductType.children, true);
		renderArgs.put("productTree", productTree.toString());
	}

	private static void buildProductTree(StringBuffer productTree,
			List<ProductType> productTypes, boolean first) {
		if (productTypes != null && productTypes.size() > 0) {
			if (first) {
				productTree.append("<ul class='dropdown-menu'>");
			} else {
				productTree
						.append("<ul class='dropdown-menu submenu-show submenu-hide'>");
			}
			for (ProductType productType : productTypes) {
				Map<String, Object> args = new HashMap<String, Object>();
				args.put("urlKey", StringUtils.isNotEmpty(productType.urlKey)?productType.urlKey:productType.id);
				if (productType.children.size() > 0) {
					productTree
							.append("<li class='dropdown submenu'><a class='dropdown-toggle' data-toggle='dropdown' href='");
				} else {
					productTree.append("<li><a href='");
				}
				productTree.append(Router.reverse("Front.productList", args));
				productTree.append("'>");
				productTree.append(productType.name);
				productTree.append("</a>\n");
				buildProductTree(productTree, productType.children, false);
				productTree.append("</li>\n");
			}
			productTree.append("</ul>\n");
		}
	}
	
	public static void productList(String urlKey){
		ProductType productType;
		if(StringUtils.isEmpty(urlKey)){
			productType = ProductType.findById(ProductType.getRootId());
		}
		Logger.debug("url key: %s", urlKey);
		productType = ProductType.findByUrlKey(urlKey);
		if(productType==null && NumberUtils.isNumber(urlKey)){
			productType = ProductType.findById(NumberUtils.toLong(urlKey,-1));
			if(productType!=null && StringUtils.isNotEmpty(productType.urlKey)){
				redirect("Front.productList", true, productType.urlKey);
			}
		}
		
		if(productType == null){
    		redirect("/",true);
		}
    	
		List<ProductType> productTypes = productType.children;
		List<Product> products = null;
		if(urlKey!=null){
			products = Product.findProducts(productType.id, 1, 100);
			setBreadcrumbs(productType.parent.id);
		}
    	render(productType,products,productTypes);
	}
	
	public static void productDetails(String urlKey){
		if(StringUtils.isEmpty(urlKey)){
			redirect("/",true);
		}
		
		Product product = Product.findByUrlKey(urlKey);
		if(product==null && NumberUtils.isNumber(urlKey)){
			product = Product.findById(NumberUtils.toLong(urlKey,-1));
			if(product!=null && StringUtils.isNotEmpty(product.urlKey)){
				redirect("Front.productDetails",true,product.urlKey);
			}
		}
		
    	if(product==null){
    		redirect("/",true);
    	}
    	product.overview = Jsoup.clean(product.overview, whitelist);
    	List<ProductType> productTypes = product.productTypes;
    	if(productTypes.size()>0){
    		setBreadcrumbs(productTypes.get(0).id);
    	}
    	render(product);
	}

	public static void viewContent(String type1,String type2){
		if("home".equals(type1)){
			loadNews();
		}
		
		StringBuffer template = new StringBuffer();
		template.append("/Front/").append(type1);
		if(StringUtils.isNotEmpty(type2)){
			template.append("/").append(type2);
		}
		template.append(".html");
		renderTemplate(template.toString());
	}
	
	public static void newsList(){
		render();
	}
	
	public static void newsView(long newsId){
		loadNews();
		News news = News.findById(newsId);
		news.content = Jsoup.clean(news.content, Whitelist.relaxed());
		render(news);
	}
	
	public static void sendMessage(@Valid Message msg){
		String referer = request.headers.get("referer").value();
		Logger.debug("referer:%s", referer);
		if(Validation.hasErrors()){
			params.flash();
			validation.keep();
		}else{
			msg.referer = referer;
			msg.save();
			notifiers.Mails.sendMessage(msg);
			flash.success("Your message have been submited successful, We will reply asap. Thank you!");
		}
		redirect(referer);
		
	}
	
	private static void loadNews() {
		List<News> newses = News.lastest(5);
		renderArgs.put("newses", newses);
	}

	private static void setBreadcrumbs(Long productTypeId){
		List<ProductType> productTypes = new ArrayList<ProductType>();
		while(productTypeId != ProductType.getRootId()){
			ProductType productType = ProductType.findById(productTypeId);
			productTypes.add(productType);
			productTypeId = productType.parent.id;
		}
		Collections.reverse(productTypes);
		renderArgs.put("parentTypes", productTypes);
	}

}
